#include "kbddrv.h"
#include "i8042.h"
#include <uprocess.h>
#include <udri.h>
#include <stdlib.h>
#include <ustdio.h>
#include <stdio.h>
dri_driver_descriptor_t *pckbd_dri_desc;
int loophandle = 0;

void uprint(char *string){
	uwrite(1,(uint8_t *)string,strlen(string));
}
void uprinti(uint32_t i){
	char bufx[12];
	itoa(i,10,bufx);
	uprint(bufx);
}
uint32_t pckbd_read(struct vfs_node *node ,uint8_t *buffer ,uint32_t offset ,uint32_t length,uint32_t fflags){
	printf("PCKBD_READ(%x,%x,%x,%x,%x)\n",node,buffer,offset,length,fflags);
	if (fflags & 0x4000){
		if (uavail(loophandle) == 0)
			return 0;
		if (length > uavail(loophandle))
			length = uavail(loophandle);
	}
	return uread(loophandle,buffer,length);
}

uint32_t pckbd_write(struct vfs_node *node ,uint8_t *buffer ,uint32_t offset ,uint32_t length,uint32_t fflags){
	return 0;
}

int main(int argc,char **argv){
	uprint("PCKBD Driver initializing...");
	pckbd_dri_desc = (dri_driver_descriptor_t *) malloc(sizeof(dri_driver_descriptor_t));
	/* Set up DRI descriptor */
	strcpy(pckbd_dri_desc->driver_name,"IBM-PC Keyboard");
	pckbd_dri_desc->driver_magic = DRI_DRIVER_MAGIC;
	pckbd_dri_desc->driver_class = DRI_CLASS_CHAR;
	pckbd_dri_desc->driver_id    = 1;
	pckbd_dri_desc->driver_class_desc = (void *) 0;
	/* Register driver with DRI */
	dri_register_driver(pckbd_dri_desc);
	/* Register devfs handles */
	dri_register_specfile("rawkbd",VFS_CHARDEVICE_FLAG,0,0x1B6,pckbd_read,pckbd_write);
	/* Create loopback buffer */
	loophandle = umkloop(512*3);//512 buffer
	/* Register IRQ */
	dri_register_interrupt(1,kbd_isr);
	/* Set kbd to a known state */
	kb_initialize();
	uprint("OK\n");
}
